package com.agricultural.machine.chain;

import java.util.ArrayList;
import java.util.List;

/**
 * 安全管理器类 - 责任链模式的客户端
 */
public class SafetyManager {
    private static SafetyManager instance;
    private final SafetyHandler chain;
    private final List<SafetyEvent> eventHistory;
    
    private SafetyManager() {
        // 构建责任链
        SafetyHandler emergencyHandler = new EmergencyHandler();
        SafetyHandler obstacleHandler = new ObstacleHandler();
        SafetyHandler faultHandler = new FaultHandler();
        
        // 设置链的顺序: 紧急情况 -> 障碍物 -> 故障
        emergencyHandler.setNext(obstacleHandler);
        obstacleHandler.setNext(faultHandler);
        
        // 设置责任链的头部
        this.chain = emergencyHandler;
        this.eventHistory = new ArrayList<>();
    }
    
    public static synchronized SafetyManager getInstance() {
        if (instance == null) {
            instance = new SafetyManager();
        }
        return instance;
    }
    
    /**
     * 处理安全事件
     */
    public void handleSafetyEvent(SafetyEvent event) {
        System.out.println("安全管理器收到事件: " + event.getEventType() + " - " + event.getDescription());
        
        // 添加到历史记录
        eventHistory.add(event);
        
        // 传递给责任链处理
        boolean handled = chain.handle(event);
        
        if (!handled) {
            System.out.println("警告：没有处理器能处理此事件: " + event.getEventType());
        }
    }
    
    /**
     * 获取事件历史
     */
    public List<SafetyEvent> getEventHistory() {
        return new ArrayList<>(eventHistory);
    }
    
    /**
     * 获取未处理的事件
     */
    public List<SafetyEvent> getUnhandledEvents() {
        List<SafetyEvent> unhandledEvents = new ArrayList<>();
        for (SafetyEvent event : eventHistory) {
            if (!event.isHandled()) {
                unhandledEvents.add(event);
            }
        }
        return unhandledEvents;
    }
    
    /**
     * 清除事件历史
     */
    public void clearEventHistory() {
        eventHistory.clear();
    }
} 